package com.ss.web;

import com.ss.pojo.Message;
import com.ss.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;


@Controller
public class ChatController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private static final String SUBSCRIBE_MESSAGE_URI = "/topic/chat/message"; //订阅接收消息地址

	private static final String IMAGE_PREFIX = "/resources/media/image/";  //服务器储存上传图片地址的前缀
	@Autowired
	private SimpMessagingTemplate messagingTemplate;
	@Autowired
	private MessageService messageService;
	@MessageMapping("/chat/message")
	public void receiveMessage(Message message){
		message.setTime(new Date());
		message.setType("text");
		//保存聊天信息
		messageService.record(message.getUserID(), message.getTime(), message.getContent(), message.getType());
		messagingTemplate.convertAndSend(SUBSCRIBE_MESSAGE_URI, message);
	}

	@RequestMapping(value = "/upload/image", method = RequestMethod.POST)
	@ResponseBody

	public String handleUploadImage(HttpServletRequest request, @RequestParam("image") MultipartFile imageFile,
	                                @RequestParam("userID")String userID){
		if (!imageFile.isEmpty()){
			String imageName = userID + "_" + (int)(Math.random() * 1000000) + ".jpg";
			String path = request.getSession().getServletContext().getRealPath(IMAGE_PREFIX)  +"/" + imageName;
			File localImageFile = new File(path);
			try {
				//上传图片到目录
				byte[] bytes = imageFile.getBytes();
				BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(localImageFile));
				bufferedOutputStream.write(bytes);
				bufferedOutputStream.close();
				Message message = new Message();
				message.setType("image");
				message.setUserID(userID);
				message.setTime(new Date());
				message.setContent(request.getContextPath() + IMAGE_PREFIX + imageName);

				//保存发送图片信息
				messageService.recordMessage(message);

				messagingTemplate.convertAndSend(SUBSCRIBE_MESSAGE_URI, message);
			} catch (IOException e) {
				logger.error("图片上传失败：" + e.getMessage(), e);
				return "upload false";
			}
		}
		return "upload success";
	}
}
